package com.Sake.common.utils.ip;

import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class HttpUtils {

    @Autowired
    private HttpClientUtils httpClientUtils;

    /**
     * 获取当前Http请求的客户端ip地址
     *
     * @param request
     * @return
     */
    public String getRemortIp(HttpServletRequest request) {
        String hed = "x-forwarded-for";
        if (request.getHeader(hed) == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader(hed);
    }


    /**
     * 获取当前IP的归属地
     *
     * @param ip 当前IP
     * @return
     */
    public String getIpArea(String ip) {
        // 拼接访问地址+IP
        String url = "http://freeapi.ipip.net/" + ip;
//        String url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
        // 访问并返回数据
        JSONArray object = httpClientUtils.httpGet(url);
        System.out.println("通过IP的地址去请求返回的内容："+object);
        if (object == null){
            return "中国";
        }else {
            return object.get(1).toString() + "/" + object.get(2).toString();
        }
///        // 判断是否成功 0:成功，1:失败
///        Integer code = object.getInteger("code");
///        JSONObject data = object.getJSONObject("data");
///        if (code == 0) {
///            String region = data.getString("region");
///            String city = data.getString("city");
///            String area = region + "/" + city;
///            return area;
///        }
///        return "中国";
    }

    /**
     * 获取当前请求的url地址
     *
     * @param request
     * @return
     */
    public String getRemortUrl(HttpServletRequest request) {
        return request.getRequestURL().toString();

    }

    /**
     * 获取当前请求的用户ID
     *
     * @param request
     * @return 当前用户ID
     */
    public Long getCurrentUser(HttpServletRequest request) {
        Object object = request.getAttribute("userId");
        if (object != null) {
            return Long.valueOf(object.toString());
        }
        return 0L;
    }


}
